package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.utils.FileUploader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

  /*  @Value("${reggie.path}")
    private  String basePath ;*/
    /**
     * 文件上传
     * @param file 与前端name属性的值保持一致
     * @return
     */
   /* @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //file是临时文件,需要储存到本地
        //1获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //截取文件后缀名 以最后.截取
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //2原始文件名重名现象,重新命名(防止覆盖) UUID生成随机文件名
        String filename = UUID.randomUUID().toString()+suffix;
        //2.1 判断文件目录是否存在,健壮性判断
        File f=new File(basePath);
        if (!f.exists()){
            //不存在就创建
            f.mkdirs();
        }
        //3转存到本地
        try {
            file.transferTo(new File(basePath+filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //上传成功,返回文件名
        return R.success(filename);
    }
*/
    /**
     * 下载文件
     * @param name
     * @param response
     */
   /* @GetMapping("/download")
    public void downLoad(String name, HttpServletResponse response){
        try {
            //读取磁盘文件,获取字节输入流
            FileInputStream fis = new FileInputStream(basePath + name);
            //响应文件数据,获取字节输出流
            ServletOutputStream sos = response.getOutputStream();
            //文件对拷
            IOUtils.copy(fis,sos);//commons-io坐标
            sos.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }*/

    @Autowired
    private FileUploader fileUploader;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        String fileName = null;
        try {
            fileName = fileUploader.upload(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }
}
